import adminListView from "$v/adminList";
//映入请求
import {
  addAdminRequest,
  adminListRequest,
  deleteAdmin
} from "$a/adminListApi"

import {
  isLoginRequest
} from "$a/loginApi"

//封装渲染页面的方法
const refreshAdminList = async (res) => {
  //刚刚开始刷新界面的时候就可以进行数据列表请求
  let adminListResult = null
  try {
    adminListResult = await adminListRequest();
    // console.log('adminListResult', adminListResult);
  } catch (e) {
    alert("获取管理员列表异常:" + e.message)
    if (!e.isLogin) {
      return router.go("/login");
    }
  }

  res.render(adminListView({
    adminList: adminListResult
  }))
}

export default async (req, res) => {
  // 切换路由的时候判断权限异常
  try {
    await isLoginRequest();
  }catch (e) {
    alert("有异常"+e.message)
    if (!e.isLogin){
      return router.go("/login")
    }
  }

  await refreshAdminList(res)
  const oSaveAdmin = document.getElementById("saveAdminBtn");

  document.onclick = async function (e) {
    if (e.target.id === 'saveAdminBtn') {
      // debugger
      // console.log(document.adminForm.adminName)
      const adminNameValue = document.adminForm.adminName.value.trim();
      const passWordValue = document.adminForm.passWord.value.trim();
      const rePassWordValue = document.adminForm.rePassWord.value.trim();
      // console.log(adminNameValue,passWordValue,rePassWordValue)
      //  判断是否为空
      if (!adminNameValue || !passWordValue || !rePassWordValue) {
        return alert("您有一个单元格为空值！！")
      }
      if (passWordValue !== rePassWordValue) {
        return alert("两次输入的密码不一致!")
      }
      // console.log('账号',adminNameValue)
      // console.log('密码',passWordValue)
      try {
        await addAdminRequest({
          adminName: adminNameValue,
          passWord: passWordValue,
          regTime: new Date().toLocaleString()
        })
        alert('恭喜您，添加成功')

        document.querySelector('#closeForm').click()
        document.adminForm.reset()
        refreshAdminList(res)

      } catch (e) {
        alert('有异常' + e.message)
        document.adminForm.reset()
      }
    }
    if (e.target.nodeName === "BUTTON" && e.target.parentNode.nodeName === "TD") {
      //获取当前删除按钮对应的adminName(在生成删除按钮的时候 就把自定义属性设置上去)
      const adminName = e.target.dataset.adminname;
      // console.log(adminName);
      //发送删除请求
      try {
        await deleteAdmin(adminName);
        alert("删除管理员" + adminName + "成功")

        //删除成功 重新渲染视图
        refreshAdminList(res);
      } catch (e) {
        alert("删除管理员" + adminName + "异常")
        if (!e.isLogin) {
          return router.go("/login");
        }
      }
    }
  }
}